import json
import re

from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render
from rest_framework.decorators import authentication_classes, permission_classes, action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from auto_dj_test import pagination
from aweirunner import models, serializers
from aweirunner.utils import response
from aweirunner.utils.report import ConvertRequest


class ReportView(GenericViewSet):
    """
    报告视图
    """

    queryset = models.Report.objects  # 用于指定默认查询集，从数据库中获取的对象集合
    serializer_class = serializers.ReportSerializer  # 指定默认的序列化器
    pagination_class = pagination.MyPageNumberPagination  # 自定义分页
    permission_classes = ()

    # def get_authenticators(self):
    #     # 查看报告详情不需要鉴权
    #     # self.request.path = '/api/aweirunner/report/3053/'
    #     pattern = re.compile(r"/api/aweirunner/report/\d+/")
    #     if (
    #             self.request.method == "GET"
    #             and re.search(pattern, self.request.path) is not None
    #     ):
    #         # authentication_classes=[] 如果满足上面条件，则不需要鉴权
    #         return []
    #     # 否，就调用父类的鉴权
    #     return super().get_authenticators()

    def list(self, request):
        """报告列表"""

        project = request.query_params["project"]
        search = request.query_params["search"]
        report_type = request.query_params["reportType"]
        report_status = request.query_params["reportStatus"]
        only_me = request.query_params["onlyMe"]

        queryset = (
            self.get_queryset().filter(project__id=project).order_by("-update_time")
        )
        # 前端传过来是小写的字符串，不是python的True
        if only_me == "true":
            queryset = queryset.filter(creator=request.user['username'])


        if search != "":
            queryset = queryset.filter(name__contains=search)

        if report_type != "":
            queryset = queryset.filter(type=report_type)

        if report_status != "":
            queryset = queryset.filter(status=report_status)

        page_report = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page_report, many=True)
        return self.get_paginated_response(serializer.data)

    def delete(self,request,**kwargs):
        """
        删除报告
        删除一个 pk
        删除多个
        [{
           id: int
        }]
        """
        try:
            if kwargs.get("pk"): # 单个删除
                models.Report.objects.get(id=kwargs["pk"]).delete()
            else:
                for content in request.data:
                    models.Report.objects.get(id=content["id"]).delete()

        except ObjectDoesNotExist:
            return Response(response.REPORT_NOT_EXISTS)

        return Response(response.REPORT_DEL_SUCCESS)

    def look(self, request, **kwargs):
        """查看报告"""
        pk = kwargs["pk"]
        report = models.Report.objects.get(id=pk)
        report_detail = models.ReportDetail.objects.get(report_id=pk)
        summary = json.loads(report.summary)
        summary["details"] = eval(report_detail.summary_detail)
        # ConvertRequest.generate_curl(summary["details"], convert_type=("curl",))
        summary["html_report_name"] = report.name

        return Response(summary)